package com.coc.ofmylistener.event.support;

import com.coc.ofmylistener.event.Event;
import com.coc.ofmylistener.event.EventHandler;
import com.coc.ofmylistener.event.EventHandlerManager;
import com.coc.ofmylistener.event.EventPublisher;

import java.util.Collection;

public class SimpleEventPublisher implements EventPublisher {

    private EventHandlerManager eventHandlerManager = null;

    public SimpleEventPublisher () {}

    public SimpleEventPublisher (EventHandlerManager eventHandlerManager) {
        this.eventHandlerManager = eventHandlerManager;
    }

    @Override
    public void publish(Event event) {
        doPublish(event);
    }

    private void doPublish(Event event){
        Collection<EventHandler> handlers = eventHandlerManager.getHandlers();

        if (handlers == null){
            // logger   no event handler
        }

        for (EventHandler handler : handlers ) {
            if (handler.canHandler(event)){
                try{
                    handler.handler(event);
                }catch (RuntimeException e ) {
                    // logger :
                    throw e;
                }catch (Exception e){
                    // logger :
                    throw new RuntimeException(e);
                }

            }
        }

    }


    @Override
    public void setEventHandlerManager(EventHandlerManager manager) {
        this.eventHandlerManager = manager;
    }
}
